<?php
namespace App\Http\Controllers\Partner;
use App\Http\Controllers\ApiBaseController;
use Illuminate\Http\Request;
use App\Models\PartnerModels\Partner;
use App\Models\OrderModels\Order;
use App\Models\PartnerModels\Keyword;
use App\Models\PartnerModels\Photo;
use App\Models\UserModels\Userinfo;
use App\Models\PartnerModels\CommentUser;
class VipAjaxController extends ApiBaseController{
	public function __construct(Request $request) {
		parent::__construct($request);
	}
    //会员列表
	public function dataList(){
		$oPartner = new Partner();
		$result = $oPartner->getVipPageData($this->params);
		echo json_encode($result);
	}
    function viewInfo(){
		$oPartner = new Partner();
		$re=$oPartner->viewVipInfo($this->params['kid']);
		if($re){
			$this->returnJson(0,$re);
		}
		$this->returnJson(1,"数据错误");
	}

    //关键词拉取	type 0内容关键词 否则 标题关键词
    function getKey(){
        $oKeyword = new Keyword();
        $type=isset($this->params['type']) ? intval($this->params['type']) : 0;
        $userid=isset($this->params['id']) ? intval($this->params['id']) : 0;
    //  print_r($userid);exit();
        $result = $oKeyword->getKeyData($type,$userid);
        echo json_encode($result);
    }
    //修改关键词状态	type 0内容关键词 否则 标题关键词
    function upStatus(){
        $oKeyword = new Keyword();
        $userid=isset($this->params['userid']) ? intval($this->params['userid']) : 0;
        $kid=isset($this->params['kid']) ? intval($this->params['kid']) : 0;
        $status=isset($this->params['status']) ? intval($this->params['status']) : 0;
        $type=isset($this->params['type']) ? intval($this->params['type']) : 0;
        $result = $oKeyword->upStatusKey($userid,$kid,$status,$type);
        $result ? ( $result==99 ? $this->returnJson(1,'最多同时开启15个') : $this->returnJson(0,'操作成功') ) : $this->returnJson(1,'操作失败');
    }
    //保存关键词	type 0内容关键词 否则 标题关键词
    function saveKey(){
        $oKeyword = new Keyword();
        $user_id=isset($this->params['userid']) ? intval($this->params['userid']) : 0;
        $kid=isset($this->params['kid']) ? intval($this->params['kid']) : 0;
        $name=isset($this->params['name']) && $this->params['name'] ? $this->params['name'] : $this->returnJson(1,'请填写关键词');
        $type=isset($this->params['type']) ? intval($this->params['type']) : 0;
        $checkKey=$oKeyword->checkKey($type,$name,$kid);
        !$checkKey ? '' : $this->returnJson(1,'请不要重复添加该关键词');
        $data=[
            'name'=>htmlspecialchars($name,ENT_QUOTES),
            'user_id'=>$user_id,
            'update_time'=>date('Y-m-d H:i:s'),
            'status'=>1,
        ];
        if($type){
            $getKeyDataUp=$oKeyword->getKeyDataUp();
            if($getKeyDataUp>=15){
                $data['status']=0;
            }
        }
        $result = $oKeyword->saveKey($kid,$data,$type);
        $result ? $this->returnJson(0,'操作成功') : $this->returnJson(1,'操作失败');
    }

    //拉取会员的收藏详情
    function ShoucangData(){
        $partner_id=isset($this->params['kid']) ? intval($this->params['kid']) : 0;
        $oPartner = new Partner();
        $data=$oPartner->getshoucangPageData($partner_id);
        //   print_r($data);exit();
        $this->returnJson(0,$data);
    }
    //拉取会员获客信息
    function huokeData(){
        $partner_id=isset($this->params['kid']) ? intval($this->params['kid']) : 0;
        $oPhoto = new Photo();
        $keywordcount=$oPhoto->getKeywordCenter($partner_id);
        $videocount=$oPhoto->getVideoCenter($partner_id,2);
        $ggcount=$oPhoto->getVideoCenter($partner_id,3);
        $drcount=$oPhoto->getdrCenter($partner_id,1);
   //  print_r($ggcount);exit();
        $daysx=$ggcount['daysx'];
        $monthsx=$ggcount['monthsx'];
        $weeksx=$ggcount['weeksx'];
        $allsx=$ggcount['allsx'];
        $day=$ggcount['day'];
        $week=$ggcount['week'];
        $month=$ggcount['month'];
        $all=$ggcount['all'];
        $html='';
        if(isset($keywordcount)){
            $html.="<tr><td>询盘数据</td>";
            $html.="<td>{$keywordcount['daysx']}</td>";
            $html.="<td>{$keywordcount['weeksx']}</td>";
            $html.="<td>{$keywordcount['monthsx']}</td>";
            $html.="<td>{$keywordcount['allsx']}</td>";
            $html.="<td>{$keywordcount['day']}</td>";
            $html.="<td>{$keywordcount['week']}</td>";
            $html.="<td>{$keywordcount['month']}</td>";
            $html.="<td>{$keywordcount['all']}</td>";
            $html.="</tr>";
            $html.="<tr><td>账号雷达数据</td>";
            $html.="<td>{$drcount['daysx']}</td>";
            $html.="<td>{$drcount['weeksx']}</td>";
            $html.="<td>{$drcount['monthsx']}</td>";
            $html.="<td>{$drcount['allsx']}</td>";
            $html.="<td>{$drcount['day']}</td>";
            $html.="<td>{$drcount['week']}</td>";
            $html.="<td>{$drcount['month']}</td>";
            $html.="<td>{$drcount['all']}</td>";
            $html.="</tr>";
            $html.="<tr><td>视频雷达数据</td>";
            $html.="<td>{$videocount['daysx']}</td>";
            $html.="<td>{$videocount['weeksx']}</td>";
            $html.="<td>{$videocount['monthsx']}</td>";
            $html.="<td>{$videocount['allsx']}</td>";
            $html.="<td>{$videocount['day']}</td>";
            $html.="<td>{$videocount['week']}</td>";
            $html.="<td>{$videocount['month']}</td>";
            $html.="<td>{$videocount['all']}</td>";
            $html.="</tr>";
            $html.="<tr><td>广告雷达数据</td>";
            $html.="<td>{$daysx}</td>";
            $html.="<td>{$weeksx}</td>";
            $html.="<td>{$monthsx}</td>";
            $html.="<td>{$allsx}</td>";
            $html.="<td>{$day}</td>";
            $html.="<td>{$week}</td>";
            $html.="<td>{$month}</td>";
            $html.="<td>{$all}</td>";
            $html.="</tr>";
            $html.="<tr><td>直播雷达数据</td>";
            $html.="<td>{$videocount['daysx']}</td>";
            $html.="<td>{$videocount['weeksx']}</td>";
            $html.="<td>{$videocount['monthsx']}</td>";
            $html.="<td>{$videocount['allsx']}</td>";
            $html.="<td>{$videocount['day']}</td>";
            $html.="<td>{$videocount['week']}</td>";
            $html.="<td>{$videocount['month']}</td>";
            $html.="<td>{$videocount['all']}</td>";
            $html.="</tr>";
        }
       // print_r($html);exit();
        $data['msg']=$html;
        $this->returnJson(0,$html);
    }
        //总后台拉取会员的雷达数据
    //   合伙人拉取雷达列表数据
    function getLeidaData(){
        $partner_id=isset($this->params['kid']) ? intval($this->params['kid']) : 0;
        $type=isset($this->params['type']) ? intval($this->params['type']) : 0;
        $day=isset($this->params['day']) ? intval($this->params['day']) : 0;
        $page = isset($this->params['page']) && intval($this->params['page']) ? intval($this->params['page']) : 1;
//        $name=isset($this->params['name']) ? intval($this->params['name']) : 0;
        //   print_r($day);exit();
        $ophoto = new Photo();
        $re=$ophoto->getLeiDaDate($partner_id,$type,$day,$page);
        echo json_encode(["code" => 0, "html" => $re['html'], "nextPage" => $re['nextPage']]);
    }
    //ajax拉取指定	视频、主页	相关评论		type 0视频 否则主页
    function getVideoComment()
    {
        $userInfo = new Userinfo();
        $video_id = isset($this->params['video_id']) ? $this->params['video_id'] : 0;
        $type = isset($this->params['type']) ? intval($this->params['type']) : 0;
        $page = isset($this->params['page']) && intval($this->params['page']) ? intval($this->params['page']) : 1;
        $hour = isset($this->params['hour']) ? intval($this->params['hour']) : 0;
        $day = isset($this->params['day']) ? intval($this->params['day']) : 0;
        $week = isset($this->params['week']) ? intval($this->params['week']) : 0;
        $re = $userInfo->getVideoComment($video_id, $type,$page,$hour,$day,$week);
     //   print_r($type);exit();
        echo json_encode(["code" => 0, "html" => $re['html'], "nextPage" => $re['nextPage']]);
        exit;
    }
    //主页、视频	评论处理状态操作
    function commentStatus()
    {

        $CommentUser = new CommentUser();
        $kid = isset($this->params['kid']) ? intval($this->params['kid']) : 0;
        $nowStatus = $CommentUser->selectComStatus($kid);

        $returnUp = 0;
        if ($nowStatus == 1) {
            $returnUp = $CommentUser->saveStatus($kid, ['status' => 0]);
        } elseif ($nowStatus == 0) {
            $returnUp = $CommentUser->saveStatus($kid, ['status' => 1]);
        }

        $returnUp ? $this->returnJson(0, "操作成功") : $this->returnJson(1, "操作失败");
    }

    /**
    * 操作状态
    * 开启/关闭
    */
	public function deleteData(){
	    $this->params['update_time']=date('Y-m-d H:i:s',time());
		if(isset($this->params['id']) && intval($this->params['id']) > 0 && isset($this->params['status'])){
			$oPartner = new Partner();
			if($oPartner->db_update('',$this->params['id'],['status'=>$this->params['status'],'update_time'=> $this->params['update_time']])){
				$this->data = true;
			}else{
				$this->code = 1;
				$this->msg = '操作失败';
			}
		}else{
			$this->code = 1;
			$this->msg = '缺少数据';
		}
		$this->boot();
	}
	
	//添加会员操作
	public function createSave(){
		$params = $this->params;
		// echo "<pre>";print_r($params);exit();
		$this->checkParams(0,$params);
		$oPartner = new Partner();
		
		$taocan=\App\Components\Tools::getOneArray('/config/inquiry.json',$params['taocan']); //选择的套餐信息
		
		//查询余额是否足够
		$balance=$oPartner->selectBalance($params['pList_id']);
		$balance<$taocan['iqprice'] ? $this->returnJson(1,'账户余额不足，请充值！') : '';
		
		//生成会员信息
		$data=[
            'createname'=>session('user')[0]['admin_name'],
			'fid'=>$params['pList_id'],
			'type'=>2,
			'user_name'=>trim($params['user_name']),
			'pwd'=>\App\Components\Tools::passwordEncryption(trim($params['pwd'])),
			'city'=>htmlspecialchars($params['city'],ENT_QUOTES),
			'company'=>htmlspecialchars($params['company'],ENT_QUOTES),
			'address'=>htmlspecialchars($params['address'],ENT_QUOTES),
			'industry_id'=>intval($params['industry_id']),
			'name'=>htmlspecialchars($params['name'],ENT_QUOTES),
			'mobile'=>$params['mobile'],
			'gender'=>intval($params['gender'])>0 ? intval($params['gender']) : 1,
			'wechat'=>htmlspecialchars($params['wechat'],ENT_QUOTES),
			'email'=>htmlspecialchars($params['email'],ENT_QUOTES),
			'create_time'=>date('Y-m-d H:i:s',time()),
			'update_time'=>date('Y-m-d H:i:s',time()),
            'customertype'=>$params['customertype'],
		];
		$kid=$oPartner->db_insertGetId($data);
		if($kid){
			//修改余额
			$newBalance=$balance-$taocan['iqprice'];
			$oPartner->upPartnerBalance($params['pList_id'],$newBalance);
			
			//金额变动记录
			$priceData=[
				'partner_id'=>$params['pList_id'],
				'old_price'=>$balance,
				'new_price'=>$newBalance,
				'num_price'=>$taocan['iqprice'],
				'create_id'=>session('user')[0]['admin_id'],
				'create_type'=>0,
				'create_time'=>date('Y-m-d H:i:s',time()),
				'price_type'=>1,
				'content'=>"会员开户，账号：({$params['user_name']})",
			];
			$oPartner->inPriceChange($priceData);
			
			//生成合伙人订单信息 start
			$orderArray=[
				'partner_id'=>$params['pList_id'],
				'partner_type'=>1,
				'type'=>2,
				'pay_type'=>5,
				'order_no'=>str_shuffle(date('YmdHis',time())).time(),
				'remark'=>"",
				'price'=>$taocan['iqprice'],
				'discount'=>0,
				'create_time'=>date('Y-m-d H:i:s',time()),
				'status'=>200,
				'title'=>"会员开户，账号：({$params['user_name']})",
			];
			$this->orderSave($orderArray);
			// end
			
			//生成会员询盘套餐信息
			$mealArr=[
				'partner_id'=>$kid,
				'meal_name'=>$params['taocan'],
				'name'=>$taocan['iqname'],
				'price'=>$taocan['iqprice'],
				'num1'=>$taocan['iqkeymber'],
				'num2'=>$taocan['iqnumber'],
				'num3'=>$taocan['iqmonumber'],
				'num4'=>$taocan['iqtopnumber'],
				'start'=>date('Y-m-d',time()),
				'end'=>date('Y-m-d',(time()+365*24*3600)),
				'created'=>date('Y-m-d H:i:s',time()),
			];
			$oPartner->saveTaocan($mealArr,0);
			
			//添加会员内容关键词
			$oPartner->addKeyConent($kid);
			
			$this->returnJson(0,'添加成功',URL('admin/vip/list'));
		}
		$this->returnJson(1,'添加失败');
	}
	
	//修改会员操作
	public function editSave(){
		$params = $this->params;
		$this->checkParams(1,$params);
		$oPartner = new Partner();
		//查询该会员是否存在
		$partnerData = $oPartner->selectVip($params['kid']);
		// echo "<pre>";print_r($partnerData);exit();
		!$partnerData ? $this->returnJson(1,'数据错误') : '';
		
		//密码更改
		$pwd=$partnerData['pwd'];//原密码
		if( trim($params['pwd']) ){
			$pwd=\App\Components\Tools::passwordEncryption(trim($params['pwd']));
		}
		
		//查询旧套餐信息
		$oPartner = new Partner();
		$oldTaocanName=$oPartner->seletMeal($params['kid']);
		
		//套餐更改判断
		$isSaveTaocan=$this->judgeTaocan($oldTaocanName['meal_name'],$params['taocan']);
		$taocan=\App\Components\Tools::getOneArray('/config/inquiry.json',$params['taocan']); //选择的套餐信息
		
		//查询余额是否足够
		$balance=$oPartner->selectBalance($params['pList_id']);
		$isSaveTaocan && $balance<$taocan['iqprice'] ? $this->returnJson(1,'账户余额不足，请充值！') : '';
		
		//生成会员信息 htmlspecialchars作用转换特色符号
		$data=array(
			'fid'=>$params['pList_id'],
			'pwd'=>$pwd,
			'city'=>htmlspecialchars($params['city'],ENT_QUOTES),
			'company'=>htmlspecialchars($params['company'],ENT_QUOTES),
			'address'=>htmlspecialchars($params['address'],ENT_QUOTES),
			'industry_id'=>intval($params['industry_id']),
			'name'=>htmlspecialchars($params['name'],ENT_QUOTES),
			'mobile'=>$params['mobile'],
			'gender'=>intval($params['gender'])>0 ? intval($params['gender']) : 1,
			'wechat'=>htmlspecialchars($params['wechat'],ENT_QUOTES),
			'email'=>htmlspecialchars($params['email'],ENT_QUOTES),
			'update_time'=>date('Y-m-d H:i:s',time()),
            'customertype'=>$params['customertype'],
		);
		$upkid=$oPartner->db_update('',$params['kid'],$data);
		if($upkid){
			if($isSaveTaocan){
				//修改余额
				$newBalance=$balance-$taocan['iqprice'];
				$oPartner->upPartnerBalance($params['pList_id'],$newBalance);
				
				//金额变动记录
				$priceData=[
					'partner_id'=>$params['pList_id'],
					'old_price'=>$balance,
					'new_price'=>$newBalance,
					'num_price'=>$taocan['iqprice'],
					'create_id'=>session('user')[0]['admin_id'],
					'create_type'=>0,
					'create_time'=>date('Y-m-d H:i:s',time()),
					'price_type'=>1,
					'content'=>"会员套餐变更，账号：({$partnerData['user_name']})",
				];
				$oPartner->inPriceChange($priceData);
				
				//生成订单信息 start
				$orderArray=array(
					'partner_id'=>$params['pList_id'],
					'partner_type'=>1,
					'type'=>2,
					'pay_type'=>5,
					'order_no'=>str_shuffle(date('YmdHis',time())).time(),
					'remark'=>"",
					'price'=>$taocan['iqprice'],
					'create_time'=>date('Y-m-d H:i:s',time()),
					'status'=>200,
					'title'=>"会员套餐变更，账号：({$partnerData['user_name']})",
				);
				$this->orderSave($orderArray);
				
				//询盘结束时间是否小于当前时间
				$newDay=strtotime($oldTaocanName['end'])<strtotime(date('Y-m-d',time())) ? strtotime(date('Y-m-d',time())) : strtotime($oldTaocanName['end']);
				//询盘套餐信息变动
				$mealArr=[
					'meal_name'=>$params['taocan'],
					'name'=>$taocan['iqname'],
					'price'=>$taocan['iqprice']+$oldTaocanName['price'],
					'num1'=>$taocan['iqkeymber']+$oldTaocanName['num1'],
					'num2'=>$taocan['iqnumber']+$oldTaocanName['num2'],
					'num3'=>$taocan['iqmonumber']+$oldTaocanName['num3'],
					'num4'=>$taocan['iqtopnumber']+$oldTaocanName['num4'],
					'end'=>date('Y-m-d',($newDay+365*24*3600)),
					'created'=>date('Y-m-d H:i:s',time()),
				];
				$oPartner->saveTaocan($mealArr,$params['kid']);
			}
			$this->returnJson(0,'修改成功',URL('admin/vip/list'));
		}
		$this->returnJson(1,'修改失败');
	}
	
	//添加修改合伙人会员 操作相应的订单信息
	public function orderSave($data){
		$order=new Order();
		$order->db_insert($data);
	}
	
	
	//判断 添加修改的 参数是否完整   type 0(添加) 1(修改)   params 数据集合
	public function checkParams($type=0,$params){
		$oPartner = new Partner();
		if(!is_array($params)){
			$this->returnJson(1,'数据错误');
		}
		if($type && !isset($params['kid'])){
			$this->returnJson(1,'数据错误');
		}
		if(!$type){
			$checkUname=\App\Components\Tools::checkUname($params['user_name']);
			!$checkUname ? $this->returnJson(1,'请正确输入5-11位 字母、数字、下划线 的用户名') : '';
			$check_uname=$oPartner->checkUname($params['user_name']);
			$check_uname ? $this->returnJson(1,'该用户名已存在') : '';
		}
		
		$checkUpwd=\App\Components\Tools::checkUpwd($params['pwd']);
		if( (!$type && !$checkUpwd) || ($type && $params['pwd'] && !$checkUpwd) ){
			$this->returnJson(1,'请正确输入6-16位字母、数字、下划线的 密码');
		}
		if(!isset($params['city']) || empty($params['city'])){
			$this->returnJson(1,'请输入所在地');
		}
		if(!isset($params['company']) || empty($params['company'])){
			$this->returnJson(1,'请输入机构');
		}
		if(!isset($params['pList_id']) || empty($params['pList_id'])){
			$this->returnJson(1,'请选择所属合伙人');
		}
		if(!isset($params['address']) || empty($params['address'])){
			$this->returnJson(1,'请输入具体地址');
		}
		if(!isset($params['industry_id']) || intval($params['industry_id'])<1){
			$this->returnJson(1,'请选择行业');
		}
		if(!isset($params['name']) || empty($params['name'])){
			$this->returnJson(1,'请输入联系人');
		}
		$checkUmobile=\App\Components\Tools::checkUmobile($params['mobile']);
		if(!$checkUmobile){
			$this->returnJson(1,'请正确输入手机号');
		}
		/*if(!isset($params['first_price']) || intval($params['first_price'])<1){
			$this->returnJson(1,'开户金额有误！请输入大于0的值');
		}
		if(!isset($params['pay_type']) || intval($params['pay_type'])<1){
			$this->returnJson(1,'请选择支付方式');
		}
		if($params['pay_type']==4 && (!isset($params['ca_number']) || empty($params['ca_number'])) ){
			$this->returnJson(1,'请输入对公账户号');
		}*/
		if(!isset($params['taocan']) || empty($params['taocan']) || !in_array($params['taocan'],array('first','middle','tall')) ){
			$this->returnJson(1,'请选择套餐');
		}
	}
	
	//拉取会员套餐
	function listData(){
		$partner_id=isset($this->params['kid']) ? intval($this->params['kid']) : 0;
		$oPartner = new Partner();
		$data=$oPartner->selectMeal($partner_id);
		$this->returnJson(0,$data);
	}
	
	/*判断修改的套餐是否正确
	*	first 初级        	middle 中级			tall 高级
	*	oldTaocanName 修改前的会员套餐信息		true 升级套餐，false 套餐不变
	*/
	function judgeTaocan($oldTaocanName,$newTaocanName){
		if( $oldTaocanName=='first' && $newTaocanName!="first" ){
			return true;
		}elseif($oldTaocanName=='first' && $newTaocanName=="first"){
			return false;
		}elseif( $oldTaocanName=='middle' && $newTaocanName=="tall" ){
			return true;
		}elseif( $oldTaocanName=='middle' && $newTaocanName=="middle" ){
			return false;
		}elseif( $oldTaocanName=='tall' && $newTaocanName=="tall" ){
			return false;
		}else{
			$this->returnJson(1,"套餐不能降级");
		}
	}
	
	
	
	
	
	
	
	
}